package com.traffic.util;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/26
 */

import cn.hutool.core.util.ObjectUtil;
import com.traffic.annotation.Power;
import com.traffic.constant.Const;
import com.traffic.constant.Status;
import com.traffic.entity.Admin;
import com.traffic.entity.Role;
import com.traffic.exception.BaseException;
import com.traffic.mapper.RoleMapper;
import com.traffic.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * 权限处理工具类
 */
@Component
@Slf4j
public class PowerUtil {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 权限检查
     * @param method 调用该函数的方法 可用下方法获取
     * Method method = this.getClass().getDeclaredMethod(Thread.currentThread().getStackTrace()[1].getMethodName()); 需要try-catch
     * @return 无权限无需处理 函数中抛出异常 全局返回错误处理
     */
    public void authCheck(Method method) {
        // 先做一层token验证
        String account = jwtUtil.getAccount(Const.TAG_ADMIN);
        if (!jwtUtil.confirm(account)) {
            throw new BaseException(Status.NOT_ERROR);
        }

        Admin admin = adminService.get(account);
        if (!ObjectUtil.isNotNull(admin)) {
            throw new BaseException(Status.NOT_ERROR);
        }
        Long roleId = admin.getRole();
        Role role = roleMapper.selectById(roleId);
        String auth = role.getAuthority();
        List<String> authList = Arrays.asList(auth.split(Const.STRING_SPLIT));
        Power power = method.getAnnotation(Power.class);
        // 函数上存在权限相关注解
        if (ObjectUtil.isNotNull(power)) {
            String needAuth = power.authority();
            log.info("【权限要求】:{}",needAuth);
            log.info("【拥有权限】:{}",authList.toString());
            if (authList.contains(needAuth)) {
                // pass
                log.info("【权限验证通过】");
                return;
            }else {
                throw new BaseException(Status.TOKEN_ERROR);
            }
        }
        // power为空
        throw new BaseException(Status.UNKNOWN_ERROR);
    }
}
